//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.group;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.Globals;

import com.broadvision.data.client.DataManager;
import com.broadvision.system.accesscontrol.client.*;
import com.broadvision.visitor.client.VisitorManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.visitor.client.VisitorContext;
import com.broadvision.visitor.client.VisitorGroupManager;
import com.broadvision.visitor.interfaces.VisitorGroup;

import com.broadvision.portal.services.PortalVisitor;
import com.broadvision.portal.services.OrganizationObjectInfo;

import com.broadvision.manage.common.tools.user.UserProfile;
import com.broadvision.manage.tools.action.BaseAction;
import com.broadvision.manage.common.tools.action.user.UserUtils;


/**
 * Deletes a group.
 */
public class GroupDeleteAction extends BaseAction {

  public static final VisitorManager visitorMgr = new VisitorManager();

  /**
   * Implements the action for browsing a group.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                               throws Exception
  {
    try {

      // Retrieve serviceName
      PortalVisitor agent = getPortalVisitor(request);
      VisitorContext vc = agent.getContext();
      int serviceId = vc.getServiceId();
      String serviceName = DataManager.getServiceName(serviceId);

      boolean oneOnly = ((Boolean) UserUtils.getP(form, "oneOnly")).booleanValue();
      
      String groupFQN = (String) UserUtils.getP(form, "groupFQN");

      if ("root".equals(groupFQN)) {
	request.setAttribute(Globals.ERROR_KEY, "error.application");
	return mapping.findForward("failure");
      }
      else if (!UserUtils.isEmptyString(groupFQN)) {
        int ind = groupFQN.indexOf(":");
	String groupContext = groupFQN.substring(0, ind);
	VisitorGroupManager vGroupMgr = null;
	try {        
	  vGroupMgr = new VisitorGroupManager(groupContext);
	}
	catch(Exception ex) {
          ex.printStackTrace();
	}
	  
	if ((null == vGroupMgr) || !vGroupMgr.isRootContextValid()) {
          request.setAttribute(Globals.ERROR_KEY, "error.application");
	  return mapping.findForward("failure");
	}

        vGroupMgr.setServiceName(serviceName);

	AccessManager aclMgr = AccessManager.instance();

	if (oneOnly) {
	  String subGroupFQN = (String) UserUtils.getP(form, "subGroupFQN");
	  VisitorGroup thisGroup = vGroupMgr.getVisitorGroupByFqn(subGroupFQN);

	  // need to clean up the admin first
	  try {
            OrganizationObjectInfo org = new OrganizationObjectInfo(thisGroup);
	    ArrayList admins = (ArrayList) aclMgr.getPrincipalsInRole(UserProfile.ORGANIZATION_ADMIN, org);
	    if (null != admins) {
              for (int j = 0; j < admins.size(); j++) {
	        Visitor v = (Visitor) admins.get(j);
		aclMgr.revokeRole(v, UserProfile.ORGANIZATION_ADMIN, org);
	      } 
	    }
	  }
	  catch (Exception ex) {
	  }
	  vGroupMgr.deleteVisitorGroup(thisGroup);
	}
	else {
	  String[] groupFQNs = (String[]) UserUtils.getP(form, "groupFQNs");
	  for (int i = 0; i < groupFQNs.length; i++) {
	    VisitorGroup thisGroup = vGroupMgr.getVisitorGroupByFqn(groupFQNs[i]);
	    // need to clean up the admin first
	    try {
              OrganizationObjectInfo org = new OrganizationObjectInfo(thisGroup);
	      ArrayList admins = (ArrayList) aclMgr.getPrincipalsInRole(UserProfile.ORGANIZATION_ADMIN, org);
	      if (null != admins) {
                for (int j = 0; j < admins.size(); j++) {
	          Visitor v = (Visitor) admins.get(j);
		  aclMgr.revokeRole(v, UserProfile.ORGANIZATION_ADMIN, org);
		} 
	      }
	    }
	    catch (Exception ex) {
	    }
	
	    vGroupMgr.deleteVisitorGroup(thisGroup);
	  }
	}
      }
    }
    catch (Exception ex) {
	ex.printStackTrace();
	request.setAttribute(Globals.ERROR_KEY, "error.application");
	return mapping.findForward("failure");
    }
    return mapping.findForward("success");
  }
}
